// NutritionRecordScreen.kt
package com.example.nutritionmanager.record

import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.nutritionmanager.AIChatCard
import com.example.nutritionmanager.bodys.responseBodys.Nutrition
import com.example.nutritionmanager.viewModels.NutritionState
import com.example.nutritionmanager.viewModels.NutritionViewModel
import com.example.nutritionmanager.buttons.PrimaryButton
import com.example.nutritionmanager.home.getCurrentDate
import com.example.nutritionmanager.viewModels.AIPromptState
import com.example.nutritionmanager.viewModels.AIPromptViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NutritionRecordScreen(
    nutritionViewModel: NutritionViewModel = hiltViewModel(),
    aiViewModel: AIPromptViewModel = hiltViewModel(),
    mealType: Int
) {
    val colorScheme = MaterialTheme.colorScheme
    val nutritionState by nutritionViewModel.nutritionState.collectAsState()
    val selectedNutritions by nutritionViewModel.selectedNutritions.collectAsState()
    val nutritionInputs by nutritionViewModel.nutritionInputs.collectAsState()
    val aiPromptState by aiViewModel.aiPromptState.collectAsState()

    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()
    val focusManager = LocalFocusManager.current

    val context = LocalContext.current
    val activity = remember { context as? Activity }

    // 下拉菜单的展开状态
    var dropdownExpanded by remember { mutableStateOf(false) }

    var aiPromptMessage by remember { mutableStateOf<String?>(null) }

    // 监听状态变化以显示 Snackbar 和进行导航
    LaunchedEffect(nutritionState) {
        when (nutritionState) {
            is NutritionState.SaveSuccess -> {
                val message = (nutritionState as NutritionState.SaveSuccess).message
                snackbarHostState.showSnackbar(message)
                // 根据需要清空输入
                // nutritionViewModel.resetState() // 可选择重置状态
                // 导航到主页面
            }
            is NutritionState.SaveError -> {
                val errorMessage = (nutritionState as NutritionState.SaveError).error
                snackbarHostState.showSnackbar(errorMessage)
                nutritionViewModel.resetState()
            }
            is NutritionState.Error -> {
                val errorMessage = (nutritionState as NutritionState.Error).error
                snackbarHostState.showSnackbar(errorMessage)
                nutritionViewModel.resetState()
            }
            else -> {}
        }
    }

    // 计算下拉菜单中可用的营养成分
    val availableNutritions = when (nutritionState) {
        is NutritionState.Success -> {
            val allNutritions = (nutritionState as NutritionState.Success).nutritions
            allNutritions.filter { nutrition ->
                !selectedNutritions.any { it.nutritionId == nutrition.nutritionId }
            }
        }
        else -> emptyList()
    }

    // 表单验证，确保所有选定的营养成分都有有效的输入
    val isFormValid = selectedNutritions.isNotEmpty() && selectedNutritions.all { nutrition ->
        val value = nutritionInputs[nutrition.nutritionId]
        value?.isNotBlank() == true && value.toDoubleOrNull() != null
    }

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text("记录", color = colorScheme.onPrimary) },
                navigationIcon = {
                    IconButton(onClick = { activity?.finish() }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = colorScheme.onPrimary // 将箭头颜色设置为白色
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = colorScheme.primary
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState()) // 使页面可垂直滑动
                .background(colorScheme.background)
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.Top
        ) {
            Text(
                text = "记录餐食营养",
                fontSize = 22.sp,
                color = colorScheme.onBackground,
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            // 显示已选的营养成分列表，并在每项之间添加分割线
            Card(
                modifier = Modifier
                    .fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = colorScheme.surface),
                shape = MaterialTheme.shapes.medium
            )  {
                Column {
                    // 显示已选的营养成分列表
                    selectedNutritions.forEachIndexed { index, nutrition ->
                        NutrientItem(
                            nutrition = nutrition,
                            inputValue = nutritionInputs[nutrition.nutritionId] ?: "",
                            onValueChange = { value ->
                                nutritionViewModel.updateNutritionInput(nutrition.nutritionId, value)
                            },
                            onRemove = {
                                nutritionViewModel.removeNutrition(nutrition)
                            }
                        )
                        // 在每项之间添加 Divider，除了最后一项
                        if (index < selectedNutritions.size - 1) {
                            Spacer(modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).height(1.dp).border(1.dp, Color.LightGray))
                        } else {
                            Spacer(modifier = Modifier.height(8.dp))
                        }
                    }
                    // 添加营养成分的下拉菜单
                    Row (
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 8.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ){
                        OutlinedButton(
                            onClick = { dropdownExpanded = true },
                            modifier = Modifier.weight(2f)
                                .fillMaxWidth()
                                .padding(14.dp),
                            colors = ButtonDefaults.outlinedButtonColors(
                                containerColor = colorScheme.surface
                            )
                        ) {
                            Icon(
                                imageVector = Icons.Default.Add,
                                contentDescription = "添加",
                                tint = colorScheme.onSurface,
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text(text = "添加营养成分", color = colorScheme.onSurface)
                        }
                        // 问问AI按钮
                        Button(
                            onClick = {
                                val nutritionData = selectedNutritions.joinToString(", ") {
                                    "${it.nutritionName}: ${nutritionInputs[it.nutritionId]}${it.unit}"
                                }
                                when(aiPromptState){
                                    AIPromptState.Idle -> {}
                                    AIPromptState.Loading -> {}
                                    is AIPromptState.Success -> {
                                        aiPromptMessage = (aiPromptState as AIPromptState.Success).prompt + "当前摄入食物营养数据：$nutritionData"
                                    }
                                    is AIPromptState.Error -> {}
                                }
                            },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.primary
                            ),
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 14.dp)
                                .padding(end = 10.dp)
                        ) {
                            Text(text = "问问AI", color = colorScheme.onPrimary)
                        }
                    }
                    DropdownMenu(
                        expanded = dropdownExpanded,
                        onDismissRequest = { dropdownExpanded = false },
                        modifier = Modifier
                            .widthIn(max = 250.dp) // 限制下拉菜单的最大宽度
                            .background(colorScheme.surface)
                    ) {
                        availableNutritions.forEach { nutrition ->
                            DropdownMenuItem(
                                text = { Text(text = nutrition.nutritionName, color = colorScheme.onSurface) },
                                onClick = {
                                    nutritionViewModel.addNutrition(nutrition)
                                    dropdownExpanded = false
                                }
                            )
                        }
                        if (availableNutritions.isEmpty()) {
                            DropdownMenuItem(
                                text = { Text(text = "没有更多营养成分") },
                                onClick = { /* 不做任何操作 */ },
                                enabled = false
                            )
                        }
                    }
                }
            }
            Spacer(modifier = Modifier.height(24.dp))
            // AI对话标题
            Text(
                text = "AI建议",
                fontSize = 18.sp,
                color = Color.Black,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
            )
            // AI 对话卡片
            AIChatCard(
                externalMessage = aiPromptMessage,
                onExternalMessageProcessed = { aiPromptMessage = null }
            )
            // 保存按钮
            PrimaryButton(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                text = "保存",
                onClick = {
                    focusManager.clearFocus()
                    if (isFormValid) {
                        // 调用 ViewModel 的保存方法
                         nutritionViewModel.saveNutritionRecord(getCurrentDate(), mealType)
                    } else {
                        scope.launch {
                            snackbarHostState.showSnackbar("请填写所有必填项且确保输入有效")
                        }
                    }
                },
            )
        }
    }
}

@Composable
fun NutrientItem(
    nutrition: Nutrition,
    inputValue: String,
    onValueChange: (String) -> Unit,
    onRemove: () -> Unit
) {
    val colorScheme = MaterialTheme.colorScheme

    Column(
        modifier = Modifier
            .fillMaxWidth()
//            .padding(vertical = 4.dp) // 减少垂直内边距
            .background(color = colorScheme.surface)
            .padding(4.dp) // 减少内层内边距
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "${nutrition.nutritionName} (${nutrition.unit})",
                fontSize = 14.sp, // 可选：减小字体大小
                color = colorScheme.onSurface,
                modifier = Modifier.weight(1f).padding(start = 8.dp)
            )
            IconButton(onClick = { onRemove() }) {
                Icon(
                    modifier = Modifier.size(16.dp),
                    imageVector = Icons.Default.Delete,
                    contentDescription = "移除",
                    tint = Color.Gray
                )
            }
        }
        // 输入框部分
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp) // 增加输入框与父容器左右边框的间距
                .height(40.dp)
                .background(color = colorScheme.surfaceVariant, shape = RoundedCornerShape(4.dp)),
            contentAlignment = Alignment.Center // 内容在Box中居中
        ) {
            BasicTextField(
                value = inputValue,
                onValueChange = onValueChange,
                singleLine = true,
                textStyle = TextStyle(
                    fontSize = 16.sp,
                    color = colorScheme.onSurface
                ),
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Done
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 12.dp) // 调整文本与输入框边缘的内间距
            )
        }
    }
}
